package com.kosam.demoservice.repository.impl;

import com.kosam.commons.base.util.CommonUtils;
import com.kosam.commons.base.util.StringUtils;
import com.kosam.demoservice.entity.User;
import com.kosam.demoservice.repository.UserRepositoryCustom;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tgx on 2017/2/17.
 */
public class UserRepositoryImpl implements UserRepositoryCustom {

    @Resource
    private EntityManager entityManager;

    @Override
    public Page<User> query(Pageable pageable, String name) {
        StringBuilder sql = new StringBuilder();
        Map<String, Object> paramMap = new HashMap<String, Object>();

        if (StringUtils.isNotBlank(name)) {
            sql.append(" and name =:name");
            paramMap.put("user", name);
        }

        Query query = entityManager.createNativeQuery("SELECT t.* FROM user t WHERE 1=1 " + sql.toString(), User.class);
        CommonUtils.formatQueryParameter(query, paramMap);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<User> resultList = query.getResultList();

        Query totalQuery = entityManager.createNativeQuery("SELECT count(*) FROM user t WHERE 1=1 " + sql.toString());
        CommonUtils.formatQueryParameter(totalQuery, paramMap);
        int total = ((BigInteger) totalQuery.getSingleResult()).intValue();

        return new PageImpl<User>(resultList, pageable, total);
    }
}
